<?php
/**
 * autorize.net Standard payment method class
 *
 * @package paymentMethod
 * @copyright Copyright 2003-2006 Zen Cart Development Team
 * @copyright Portions Copyright 2003 osCommerce
 * @license http://www.zen-cart.com/license/2_0.txt GNU Public License V2.0
 * @version $Id: gspay.php 4275 2006-08-26 03:18:04Z drbyte $
 */
/**
 * Enter description here...
 *
 */
class gspay extends base {
  /**
   * $code determines the internal 'code' name used to designate "this" payment module
   *
   * @var string
   */
  var $code;
  /**
   * $title is the displayed name for this payment method
   *
   * @var string
   */
  var $title;
  /**
   * $description is a soft name for this payment method
   *
   * @var string
   */
  var $description;
  /**
   * $enabled determines whether this module shows or not... in catalog.
   *
   * @var boolean
   */
  var $enabled;
  /**
   * @return gspay
   */
  function gspay() {
    global $order;

    $this->code = 'gspay';
    if ($_GET['main_page'] != '') {
      $this->title = MODULE_PAYMENT_GSPAY_TEXT_CATALOG_TITLE; // Payment module title in Catalog
    } else {
      $this->title = MODULE_PAYMENT_GSPAY_TEXT_ADMIN_TITLE; // Payment module title in Admin
    }
    $this->description = MODULE_PAYMENT_GSPAY_TEXT_DESCRIPTION;
    $this->enabled = ((MODULE_PAYMENT_GSPAY_STATUS == 'True') ? true : false);
    $this->sort_order = MODULE_PAYMENT_GSPAY_SORT_ORDER;

    if ((int)MODULE_PAYMENT_GSPAY_ORDER_STATUS_ID > 0) {
      $this->order_status = MODULE_PAYMENT_GSPAY_ORDER_STATUS_ID;
    }

    if (is_object($order)) $this->update_status();

    $this->form_action_url = 'https://secure.redirect2pay.com/payment/pay.php';
  }

  // Authorize.net utility functions
  // DISCLAIMER:
  //     This code is distributed in the hope that it will be useful, but without any warranty;
  //     without even the implied warranty of merchantability or fitness for a particular purpose.

  // Main Interfaces:
  //
  // function InsertFP ($loginid, $txnkey, $amount, $sequence) - Insert HTML form elements required for SIM
  // function CalculateFP ($loginid, $txnkey, $amount, $sequence, $tstamp) - Returns Fingerprint.

  // compute HMAC-MD5
  // Uses PHP mhash extension. Pl sure to enable the extension
  // function hmac ($key, $data) {
  //   return (bin2hex (mhash(MHASH_MD5, $data, $key)));
  //}

  // Thanks is lance from http://www.php.net/manual/en/function.mhash.php
  //lance_rushing at hot* spamfree *mail dot com
  //27-Nov-2002 09:36
  //
  //Want to Create a md5 HMAC, but don't have hmash installed?
  //
  //Use this:
  /**
   * compute HMAC-MD5
   *
   * @param string $key
   * @param string $data
   * @return string
   */
  function hmac ($key, $data)
  {
    // RFC 2104 HMAC implementation for php.
    // Creates an md5 HMAC.
    // Eliminates the need to install mhash to compute a HMAC
    // Hacked by Lance Rushing

    $b = 64; // byte length for md5
    if (strlen($key) > $b) {
      $key = pack("H*",md5($key));
    }
    $key  = str_pad($key, $b, chr(0x00));
    $ipad = str_pad('', $b, chr(0x36));
    $opad = str_pad('', $b, chr(0x5c));
    $k_ipad = $key ^ $ipad ;
    $k_opad = $key ^ $opad;

    return md5($k_opad  . pack("H*",md5($k_ipad . $data)));
  }
  // end code from lance (resume gspay.com code)

  // Calculate and return fingerprint
  // Use when you need control on the HTML output
  function CalculateFP ($loginid, $txnkey, $amount, $sequence, $tstamp, $currency = "") {
    return ($this->hmac ($txnkey, $loginid . "^" . $sequence . "^" . $tstamp . "^" . $amount . "^" . $currency));
  }
  /**
   * Inserts the hidden variables in the HTML FORM required for SIM
   * Invokes hmac function to calculate fingerprint.
   *
   * @param string $loginid
   * @param string $txnkey
   * @param float $amount
   * @param string $sequence
   * @param float $currency
   * @return string
   */

  function InsertFP ($loginid, $txnkey, $amount, $sequence, $currency = "") {
    $tstamp = time ();
    $fingerprint = $this->hmac ($txnkey, $loginid . "^" . $sequence . "^" . $tstamp . "^" . $amount . "^" . $currency);

    $str = zen_draw_hidden_field('x_fp_sequence', $sequence) .
    zen_draw_hidden_field('x_fp_timestamp', $tstamp) .
    zen_draw_hidden_field('x_fp_hash', $fingerprint);

    return $str;
  }
  // end gspay.com-provided code

  // class methods
  /**
   * calculate zone matches and flag settings to determine whether this module should display to customers or not
   *
   */
  function update_status() {
    global $order, $db;

    if ( ($this->enabled == true) && ((int)MODULE_PAYMENT_GSPAY_ZONE > 0) ) {
      $check_flag = false;
      $check = $db->Execute("select zone_id from " . TABLE_ZONES_TO_GEO_ZONES . " where geo_zone_id = '" . MODULE_PAYMENT_GSPAY_ZONE . "' and zone_country_id = '" . $order->billing['country']['id'] . "' order by zone_id");
      while (!$check->EOF) {
        if ($check->fields['zone_id'] < 1) {
          $check_flag = true;
          break;
        } elseif ($check->fields['zone_id'] == $order->billing['zone_id']) {
          $check_flag = true;
          break;
        }
        $check->MoveNext();
      }

      if ($check_flag == false) {
        $this->enabled = false;
      }
    }
  }
  /**
   * JS validation which does error-checking of data-entry if this module is selected for use
   * (Number, Owner, and CVV Lengths)
   *
   * @return string
   */
  function javascript_validation() {
    $js = '  if (payment_value == "' . $this->code . '") {' . "\n" .
    '    var cc_owner = document.checkout_payment.gspay_cc_owner.value;' . "\n" .
    '    var cc_number = document.checkout_payment.gspay_cc_number.value;' . "\n" .
    '    if (cc_owner == "" || cc_owner.length < ' . CC_OWNER_MIN_LENGTH . ') {' . "\n" .
    '      error_message = error_message + "' . MODULE_PAYMENT_GSPAY_TEXT_JS_CC_OWNER . '";' . "\n" .
    '      error = 1;' . "\n" .
    '    }' . "\n" .
    '    if (cc_number == "" || cc_number.length < ' . CC_NUMBER_MIN_LENGTH . ') {' . "\n" .
    '      error_message = error_message + "' . MODULE_PAYMENT_GSPAY_TEXT_JS_CC_NUMBER . '";' . "\n" .
    '      error = 1;' . "\n" .
    '    }' . "\n" .
    '  }' . "\n";

    return $js;
  }
  /**
   * Display Credit Card Information Submission Fields on the Checkout Payment Page
   *
   * @return array
   */
  function selection() {
    global $order;

    for ($i=1; $i<13; $i++) {
      $expires_month[] = array('id' => sprintf('%02d', $i), 'text' => strftime('%B',mktime(0,0,0,$i,1,2000)));
    }

    $today = getdate();
    for ($i=$today['year']; $i < $today['year']+10; $i++) {
      $expires_year[] = array('id' => strftime('%y',mktime(0,0,0,1,1,$i)), 'text' => strftime('%Y',mktime(0,0,0,1,1,$i)));
    }
    $selection = array('id' => $this->code,
                       'module' => $this->title,
		       /*
	       'fields' => array(array('title' => MODULE_PAYMENT_GSPAY_TEXT_CREDIT_CARD_OWNER,
	                               'field' => zen_draw_input_field('gspay_cc_owner', $order->billing['firstname'] . ' ' . $order->billing['lastname'], 'id="'.$this->code.'-cc-owner"'),
                                               'tag' => $this->code.'-cc-owner'),
                                         array('title' => MODULE_PAYMENT_GSPAY_TEXT_CREDIT_CARD_NUMBER,
                                               'field' => zen_draw_input_field('gspay_cc_number', '', 'id="'.$this->code.'-cc-number"'),
                                               'tag' => $this->code.'-cc-number'),
                                         array('title' => MODULE_PAYMENT_GSPAY_TEXT_CREDIT_CARD_EXPIRES,
                                               'field' => zen_draw_pull_down_menu('gspay_cc_expires_month', $expires_month, '', 'id="'.$this->code.'-cc-expires-month"') . '&nbsp;' . zen_draw_pull_down_menu('gspay_cc_expires_year', $expires_year),
                                               'tag' => $this->code.'-cc-expires-month')
		               )
	       */
	       );

    return $selection;
  }
  /**
   * Evaluates the Credit Card Type for acceptance and the validity of the Credit Card Number & Expiration Date
   *
   */
  function pre_confirmation_check() {
  }
  /**
   * Display Credit Card Information on the Checkout Confirmation Page
   *
   * @return array
   */
  function confirmation() {
    global $_POST;


    $confirmation = array();

    //return $confirmation;
    return true;
  }
  /**
   * Build the data and actions to process when the "Submit" button is pressed on the order-confirmation screen.
   * This sends the data to the payment gateway for processing.
   * (These are hidden fields on the checkout confirmation page)
   *
   * @return string
   */
  function process_button() {
    global $_SERVER, $order,$currencies;

    $sequence = rand(1, 1000);
      $process_button_string = zen_draw_hidden_field('siteID', MODULE_PAYMENT_GSPAY_LOGIN) .
                               zen_draw_hidden_field('orderID', $order->info['orderID']) .
                               zen_draw_hidden_field('ApproveURL',  zen_href_link(FILENAME_CHECKOUT_PROCESS, '', 'SSL')).
                               zen_draw_hidden_field('customerFullName',$order->customer[firstname]." ".$order->customer[lastname] ) .
                               zen_draw_hidden_field('customerAddress', $order->customer['street_address']) .
                               zen_draw_hidden_field('customerCity', $order->customer['city']) .
                               zen_draw_hidden_field('customerStateCode', !empty($stateCode) ? $stateCode : 'XX') .
                               zen_draw_hidden_field('customerZip', $order->customer['postcode']) .
                               zen_draw_hidden_field('customerCountry', $order->customer['country']['title']) .
                               zen_draw_hidden_field('customerEmail', $order->customer['email_address']) .
                               zen_draw_hidden_field('customerPhone', $order->customer['telephone']) .

                               zen_draw_hidden_field('customerShippingFullName',$order->delivery[firstname]." ".$order->customer[lastname] ) .
                               zen_draw_hidden_field('customerShippingAddress', $order->delivery['street_address']) .
                               zen_draw_hidden_field('customerShippingCity', $order->delivery['city']) .
                               zen_draw_hidden_field('customerShippingStateCode', !empty($deliveryStateCode) ? $deliveryStateCode: 'XX') .
                               zen_draw_hidden_field('customerShippingZip', $order->delivery['postcode']) .
                               zen_draw_hidden_field('customerShippingCountry', $order->delivery['country']['title']) .
                               zen_draw_hidden_field('customerShippingEmail', $order->delivery['email_address']) .
                               zen_draw_hidden_field('customerShippingPhone', $order->customer['telephone']) .
      				
			       "";

    $process_button_string .= zen_draw_hidden_field(zen_session_name(), zen_session_id());
	foreach ($order->products as $key => $product) {
		$add_info="";
		if (is_array($product[attributes])) foreach ($product[attributes] as $attr) {
			$add_info.=$attr[option].":".$attr[value]." ";
		}
		///////////////add liuwei bof//////////
		if(DEFAULT_CURRENCY!="USD"){
			$product['final_price']=zen_round($product['final_price']*$currencies->currencies['USD']['value']);
		}
		///////////////add liuwei eof//////////
		$process_button_string .= zen_draw_hidden_field("Amount[$key]", number_format($product['final_price'], 2)) ;
		$process_button_string .= zen_draw_hidden_field("Qty[$key]", number_format($product['qty'], 2)) ;
		$process_button_string .= zen_draw_hidden_field("OrderDescription[$key]", $product['name'].($add_info ? " ($add_info)" : "")) ;
		$hash_amount.=number_format($product['final_price'], 2)."|";
		$hash_qty.= number_format($product['qty'], 2)."|";
		$totalprice+=$product['final_price'];
	}
	
	///////////////add liuwei bof//////////
	if(DEFAULT_CURRENCY!="USD"){
		$tax=zen_round($order->info['tax']*$currencies->currencies['USD']['value']);
		$shipping_cost=zen_round($order->info['shipping_cost']*$currencies->currencies['USD']['value']);
		$total=zen_round($order->info['total']*$currencies->currencies['USD']['value']);
	}else{
		$tax=$order->info['tax'];
		$shipping_cost=$order->info['shipping_cost'];
		$total=$order->info['total'];
	}
	///////////////add liuwei eof//////////
	if ($tax>0) {
		$key++;
		$process_button_string .= zen_draw_hidden_field("Amount[$key]", number_format($tax, 2)) ;
		$process_button_string .= zen_draw_hidden_field("Qty[$key]",1) ;
		$process_button_string .= zen_draw_hidden_field("OrderDescription[$key]",'Tax') ;
		$hash_amount.=number_format($tax, 2)."|";
		$hash_qty.= "1|";
		$totalprice+=$tax;
	}
	if ($shipping_cost>0) {
		$key++;
		$process_button_string .= zen_draw_hidden_field("Amount[$key]", number_format($shipping_cost, 2)) ;
		$process_button_string .= zen_draw_hidden_field("Qty[$key]",'1') ;
		$process_button_string .= zen_draw_hidden_field("Type[$key]",'Shipping') ;
		$process_button_string .= zen_draw_hidden_field("OrderDescription[$key]",$order->info['shipping_method']) ;
		$hash_amount.=number_format($shipping_cost, 2)."|";
		$hash_qty.= "1|";
		$totalprice+=$shipping_cost;
	}
	if (($pd=$total-$totalprice)<-.05) {
		$key++;
		$process_button_string .= zen_draw_hidden_field("Amount[$key]", number_format($pd, 2)) ;
		$process_button_string .= zen_draw_hidden_field("Qty[$key]",'1') ;
		$process_button_string .= zen_draw_hidden_field("OrderDescription[$key]",'Discounts');
		$hash_amount.=number_format($pd, 2)."|";
		$hash_qty.= "1|";
	}
	$process_button_string .= zen_draw_hidden_field("Hash",md5($hash_amount.$hash_qty));

    return $process_button_string;
  }
  /**
   * Store the CC info to the order and process any results that come back from the payment gateway
   *
   */
  function before_process() {
	    global $order;
      global $_POST, $_GET;

    $this->m_orderid=$_GET['transactionTransactionID'];
	$url="https://secure.redirect2pay.com/payment/api.php";
	$values=array(
	'request'=>"
		<xml>
		<request>
		<transaction>
		        <transactionType>transactionStatus</transactionType>
		        <transactionTransactionID>".$_GET['transactionTransactionID']."</transactionTransactionID>
		</transaction>

		
		</request>
		</xml>
	
	",
	);

	foreach ($values as $key=>$value) {
		$params.="$key=".urlencode($value)."&";
	}
    

	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 180);
		 
	curl_setopt($ch, CURLOPT_POSTFIELDS, $params);

	ob_start();
	curl_exec($ch);
        if (curl_errno($ch)>0) {
	    zen_redirect(zen_href_link(FILENAME_CHECKOUT_PAYMENT, 'error_message=' . urlencode("CURL ERROR:".curl_errno($ch).":".curl_error($ch)), 'SSL', true, false));
	}
	$result = ob_get_contents();
	ob_end_clean();
	curl_close($ch);


	$requestxml=$result;
	$p = xml_parser_create();
	if (!  xml_parse_into_struct($p, $requestxml, $vals, $index)) {
		zen_redirect(zen_href_link(FILENAME_CHECKOUT_PAYMENT, 'error_message=' . urlencode(MODULE_PAYMENT_GSPAY_TEXT_ERROR_MESSAGE), 'SSL', true, false));
	}
	xml_parser_free($p);


	if (is_array($vals)) foreach ($vals as $key=>$value) {
		if ($value[type]=='complete') {
			$transinfo[$value[tag]]=trim($value[value]);
		}
	}


	if (!(($transinfo[TRANSACTIONSTATUS]=='approved' || $transinfo[TRANSACTIONSTATUS]=='test' ) && $transinfo[TRANSACTIONTYPE]=='sale')) {
		zen_redirect(zen_href_link(FILENAME_CHECKOUT_PAYMENT, 'error_message=' . urlencode($transinfo[TRANSACTIONMESSAGE]), 'SSL', true, false));
	}

						

  }
  /**
   * Post-processing activities
   *
   * @return boolean
   */
  function after_process() {
  	global $insert_id,$db ;
	
    $db->Execute("insert into " . TABLE_ORDERS_STATUS_HISTORY . " (comments, orders_id, orders_status_id, date_added) values ('gspay OrderId: " . $this->m_orderid . " ' , '". (int)$insert_id . "','" . $this->order_status . "', now() )");

	$_SESSION['order_created'] = '';
	return true;
  }
  /**
   * Used to display error message details
   *
   * @return array
   */
  function get_error() {
    global $_GET;

    $error = array('title' => MODULE_PAYMENT_GSPAY_TEXT_ERROR,
                   'error' => stripslashes(urldecode($_GET['error'])));

    return $error;
  }
  /**
   * Check to see whether module is installed
   *
   * @return boolean
   */
  function check() {
    global $db;
    if (!isset($this->_check)) {
      $check_query = $db->Execute("select configuration_value from " . TABLE_CONFIGURATION . " where configuration_key = 'MODULE_PAYMENT_GSPAY_STATUS'");
      $this->_check = $check_query->RecordCount();
    }
    return $this->_check;
  }
  /**
   * Install the payment module and its configuration settings
   *
   */
  function install() {
    global $db;
    $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Enable Authorize.net Module', 'MODULE_PAYMENT_GSPAY_STATUS', 'True', 'Do you want to accept Authorize.net payments?', '6', '0', 'zen_cfg_select_option(array(\'True\', \'False\'), ', now())");
    $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Site ID', 'MODULE_PAYMENT_GSPAY_LOGIN', '6006', 'The Site ID used for the GSPAY.com service', '6', '0', now())");
    $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Order form crypt key (optional)', 'MODULE_PAYMENT_GSPAY_TXNKEY', '', 'Transaction Key used for encrypting order data', '6', '0', now())");
    $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Sort order of display.', 'MODULE_PAYMENT_GSPAY_SORT_ORDER', '0', 'Sort order of display. Lowest is displayed first.', '6', '0', now())");
    $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, use_function, set_function, date_added) values ('Payment Zone', 'MODULE_PAYMENT_GSPAY_ZONE', '0', 'If a zone is selected, only enable this payment method for that zone.', '6', '2', 'zen_get_zone_class_title', 'zen_cfg_pull_down_zone_classes(', now())");
    $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, use_function, date_added) values ('Set Order Status', 'MODULE_PAYMENT_GSPAY_ORDER_STATUS_ID', '0', 'Set the status of orders made with this payment module to this value', '6', '0', 'zen_cfg_pull_down_order_statuses(', 'zen_get_order_status_name', now())");
  }
  /**
   * Remove the module and all its settings
   *
   */
  function remove() {
    global $db;
    $db->Execute("delete from " . TABLE_CONFIGURATION . " where configuration_key in ('" . implode("', '", $this->keys()) . "')");
  }
  /**
   * Internal list of configuration keys used for configuration of the module
   *
   * @return array
   */
  function keys() {
    return array('MODULE_PAYMENT_GSPAY_STATUS', 'MODULE_PAYMENT_GSPAY_LOGIN', 'MODULE_PAYMENT_GSPAY_TXNKEY', 'MODULE_PAYMENT_GSPAY_TESTMODE', 'MODULE_PAYMENT_GSPAY_METHOD', 'MODULE_PAYMENT_GSPAY_EMAIL_CUSTOMER', 'MODULE_PAYMENT_GSPAY_ZONE', 'MODULE_PAYMENT_GSPAY_ORDER_STATUS_ID', 'MODULE_PAYMENT_GSPAY_SORT_ORDER');
  }
}
?>
